package com.netstar.salesman_90dsp.activity;

import java.util.ArrayList;
import java.util.List;

import me.maxwin.view.XListView.IXListViewListener;

import org.apache.http.Header;
import org.joda.time.DateTime;

import roboguice.inject.InjectView;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.netstar.salesman_90dsp.R;
import com.netstar.salesman_90dsp.TitleBaseActivity;
import com.netstar.salesman_90dsp.adapter.ToadayWorkXLVAdapter;
import com.netstar.salesman_90dsp.config.WebServerConfig;
import com.netstar.salesman_90dsp.engine.ToadayWorkEngine;
import com.netstar.salesman_90dsp.model.CommonResponseModel;
import com.netstar.salesman_90dsp.model.ToadayWorkListResponseModel;
import com.netstar.salesman_90dsp.model.TodayWorkModel;

/**
 * 年度目标列表页面
 * 
 * @author zhangshuai
 * 
 */
public class YearTargetActivity extends TitleBaseActivity {
	/**
	 * 指定日期的key
	 */
	public static final String INTENT_KEY_APPOINT_DATE = "INTENT_KEY_APPOINT_DATE";
	/**
	 * 可下拉刷新折叠列表
	 */
	@InjectView(R.id.activity_today_work_xlv)
	me.maxwin.view.XListView activity_today_work_xlv;
	/**
	 * 工作数据， 日期 集合
	 */
	private List<String> todayWorkDateList = new ArrayList<String>();
	/**
	 * 工作数据， model集合
	 */
	private List<TodayWorkModel> todayWorkModelList = new ArrayList<TodayWorkModel>();
	/**
	 * 工作请求回调类
	 */
	private GetToadyWorkHttpHandler getToadyWorkHttpHandler;
	/**
	 * 工作 删除 回调类
	 */
	private DeleteToadyWorkHttpHandler deleteToadyWorkHttpHandler;
	/**
	 * 工作 删除 回调类
	 */
	private CompleteToadyWorkHttpHandler completeToadyWorkHttpHandler;
	/**
	 * 工作列表适配器
	 */
	private ToadayWorkXLVAdapter toadayWorkXLVAdapter;
	/**
	 * 今日工作业务逻辑类
	 */
	private ToadayWorkEngine toadayWorkEngine;
	/**
	 * 开始页数
	 */
	private int startPageNumber = 1;
	/**
	 * 当前页数
	 */
	private int currentPageNumber = startPageNumber;
	/**
	 * 列表长按点击事件
	 */
	private OnXLVChildClickListener onXLVChildClickListener;
	/**
	 * 列表刷新事件监听器
	 */
	private OnXLVEventListener onXLVEventListener;
	/**
	 * 点击操作dialog
	 */
	private Dialog operationDialog = null;
	/**
	 * 点击操作dialog的布局
	 */
	private View operationDialogView;
	/**
	 * 操作框中，返回按钮
	 */
	private Button operationDialogESCBt;
	/**
	 * 操作框中，删除按钮
	 */
	private Button activity_today_work_list_child_longclick_delete;
	/**
	 * 操作框中，移动按钮
	 */
	private Button activity_today_work_list_child_longclick_move;
	/**
	 * 操作框中，完成按钮
	 */
	private Button activity_today_work_list_child_longclick_complete;
	/**
	 * 传过来的时间
	 */
	private String appointDate = "";

	@Override
	public void subInitContentView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_today_work);
		// 接收传递过来的数据
		if (getIntent() != null) {
			// 判断是否包含指定日期
			if (getIntent().hasExtra(INTENT_KEY_APPOINT_DATE)) {
				appointDate = getIntent().getStringExtra(
						INTENT_KEY_APPOINT_DATE);
				appointDate = TextUtils.isEmpty(appointDate) ? "" : appointDate;
			}
		}
	}

	@Override
	public void subInitView() {
		// 设置title appointDate
		include_title_tv_activity_name.setVisibility(View.VISIBLE);
		if (TextUtils.isEmpty(appointDate)) {
			include_title_tv_activity_name
					.setText(R.string.module_name_today_work);
			include_title_bt_right.setVisibility(View.VISIBLE);
		} else {
			// 如果有指定日期，则在title展示
			try {
				include_title_tv_activity_name.setText(appointDate.substring(0,
						10));
			} catch (Exception e) {
				include_title_tv_activity_name.setText(appointDate);
				e.printStackTrace();
			}
			include_title_bt_right.setVisibility(View.GONE);
		}
		include_title_bt_right.setText(R.string.common_text_add_new);
		include_title_bt_left.setVisibility(View.VISIBLE);
		include_title_bt_left.setText(R.string.common_text_back);

	}

	@Override
	public void subInitParam() {
		toadayWorkEngine = new ToadayWorkEngine(activityContext);
		getToadyWorkHttpHandler = new GetToadyWorkHttpHandler();
		deleteToadyWorkHttpHandler = new DeleteToadyWorkHttpHandler();
		completeToadyWorkHttpHandler = new CompleteToadyWorkHttpHandler();
		toadayWorkXLVAdapter = new ToadayWorkXLVAdapter(activityContext,
				todayWorkModelList);
		// dialog 的布局
		operationDialogView = View.inflate(activityContext,
				R.layout.activity_today_work_list_item_operation_dialog, null);
		// dialog 去掉右边按钮
		operationDialogView.findViewById(R.id.include_title_bt_right_little)
				.setVisibility(View.GONE);
		// dialog 去掉左边按钮
		operationDialogView.findViewById(R.id.include_title_bt_left_little)
				.setVisibility(View.GONE);
		// dialog 设置名称
		((TextView) (operationDialogView
				.findViewById(R.id.include_title_tv_activity_name_little)))
				.setText(R.string.common_text_please_choose);
		// 操作框中的返回按钮
		operationDialogESCBt = (Button) operationDialogView
				.findViewById(R.id.include_title_bt_left_little);
		operationDialogESCBt.setText(R.string.common_text_back);
		// 删除按钮
		activity_today_work_list_child_longclick_delete = (Button) operationDialogView
				.findViewById(R.id.activity_today_work_list_child_longclick_delete);
		// 移动按钮
		activity_today_work_list_child_longclick_move = (Button) operationDialogView
				.findViewById(R.id.activity_today_work_list_child_longclick_move);
		// 完成按钮
		activity_today_work_list_child_longclick_complete = (Button) operationDialogView
				.findViewById(R.id.activity_today_work_list_child_longclick_complete);
		// 初始化，长按的dialog
		operationDialog = new Dialog(activityContext);
		operationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		operationDialog.setContentView(operationDialogView);
		// 展示列表
		activity_today_work_xlv.setAdapter(toadayWorkXLVAdapter);
		onXLVChildClickListener = new OnXLVChildClickListener();
		activity_today_work_xlv
				.setOnItemLongClickListener(onXLVChildClickListener);
		onXLVEventListener = new OnXLVEventListener();
		activity_today_work_xlv.setPullLoadEnable(true);
		activity_today_work_xlv.setXListViewListener(onXLVEventListener);
	}

	@Override
	public void subSetOnclick() {
		setOnclickWithDefaultListener(include_title_bt_left);
		setOnclickWithDefaultListener(include_title_bt_right);
		operationDialogESCBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				operationDialog.dismiss();
			}
		});
		setOnclickWithDefaultListener(activity_today_work_list_child_longclick_delete);
		setOnclickWithDefaultListener(activity_today_work_list_child_longclick_move);
		setOnclickWithDefaultListener(activity_today_work_list_child_longclick_complete);
	}

	@Override
	public void subRunSomeThing() {
	}

	@Override
	public void callbackWithDefaultListener(View view) {
		Intent intent = null;
		super.callbackWithDefaultListener(view);
		switch (view.getId()) {
		case R.id.include_title_bt_left:
			// 返回按钮
			finish();
			break;
		case R.id.include_title_bt_right:
			// 新增按钮
			intent = new Intent();
			intent.setClass(activityContext, TodayWorkAddActivity.class);
			startActivity(intent);
			break;
		case R.id.activity_today_work_list_child_longclick_delete:
			// dialog 删除按钮
			startDeleteTodayWork(onXLVChildClickListener.selectTodayWorkModel);
			operationDialog.dismiss();
			break;
		case R.id.activity_today_work_list_child_longclick_move:
			// dialog 移动按钮
			intent = new Intent();
			intent.setClass(activityContext, TodayWorkAddActivity.class);
			intent.putExtra(TodayWorkModel.INTENT_KEY,
					onXLVChildClickListener.selectTodayWorkModel);
			startActivity(intent);
			operationDialog.dismiss();
			break;
		case R.id.activity_today_work_list_child_longclick_complete:
			// dialog 完成按钮
			startCompleteTodayWork(onXLVChildClickListener.selectTodayWorkModel);
			operationDialog.dismiss();
			break;
		default:
			break;
		}
	}

	/**
	 * 开始加载数据
	 * 
	 * @param pageNumber
	 *            第几页
	 * @param isShownDialog
	 *            等待框
	 */
	private void startGetToadyWork(int pageNumber, boolean isShownDialog) {
		// 是否展示等待框，如果是列表加载，则不显示
		if (isShownDialog) {
			// 开启等待框
			waittingAlertDialog = dialogTool.getWaittingDialog(-1,
					getResources().getString(R.string.common_string_Loading));
			waittingAlertDialog.show();
		}
		// 通过网络获取数据
		asyncHttpClient.post(
				WebServerConfig.getUrl(WebServerConfig.todayWorkListAction),
				toadayWorkEngine.getRequestParams(pageNumber, appointDate),
				getToadyWorkHttpHandler);
	}

	/**
	 * 获取结束
	 */
	public void endGetToadyWork(boolean isSuccess, String msg,
			ToadayWorkListResponseModel toadayWorkListResponseModel) {
		// 取消登录框
		if (waittingAlertDialog != null) {
			waittingAlertDialog.dismiss();
			waittingAlertDialog = null;
		}
		if (isSuccess) {
			// 成功
			// 判断是否已经到了尽头，是最后一页，如果是，则页数再减回1
			if (toadayWorkListResponseModel.getToDayWorkModelList().size() == 0
					&& currentPageNumber > startPageNumber) {
				currentPageNumber -= 1;
			}
			// TODO list 排序未做
			// 将网络数据遍历加入列表
			initTodayWorkList(toadayWorkListResponseModel
					.getToDayWorkModelList());
		} else {
			// 失败
			msg = TextUtils.isEmpty(msg) ? getResources().getString(
					R.string.common_string_unknown_mistake) : msg;
			Toast.makeText(activityContext, msg, Toast.LENGTH_SHORT).show();
		}
		// 将列表回复原来的状态
		onLoadFinish();
	}

	/**
	 * 当有删除操作，加载更多 的时候，需要从新获取时间并排列
	 */
	private void initTodayWorkList(List<TodayWorkModel> toadayWorkModelListParam) {
		TodayWorkModel toadayWorkModelTMP = null;
		// 整理
		for (TodayWorkModel toadayWorkModel : toadayWorkModelListParam) {
			// 去除日期的条目
			if (TextUtils.isEmpty(toadayWorkModel.getId())) {
				continue;
			}
			/*
			 * 判断日期列表是否包含这个日期，如果不包含，则添加两个model，一个日期model,一个工作model 日期model 的 id为
			 * null，便于区分 如果包含，只添加一个工作model 这样来达到列表展示
			 */
			if (!todayWorkDateList.contains(toadayWorkModel
					.getPlanDateOnlyDate())) {
				toadayWorkModelTMP = new TodayWorkModel();
				toadayWorkModelTMP.setId(null);
				toadayWorkModelTMP.setPlanDate(toadayWorkModel.getPlanDate());
				todayWorkDateList.add(toadayWorkModel.getPlanDateOnlyDate());
				todayWorkModelList.add(toadayWorkModelTMP);
			}
			if (!todayWorkModelList.contains(toadayWorkModel)) {
				todayWorkModelList.add(toadayWorkModel);
			}
		}
		// 更新列表数据
		toadayWorkXLVAdapter.notifyDataSetChanged();
	}

	/**
	 * 删除工作
	 * 
	 * @param todayWorkModel
	 */
	private void startDeleteTodayWork(TodayWorkModel todayWorkModel) {
		// 开启等待框
		waittingAlertDialog = dialogTool.getWaittingDialog(-1, getResources()
				.getString(R.string.common_string_Loading));
		waittingAlertDialog.show();
		if (todayWorkModel != null) {
			asyncHttpClient.post(WebServerConfig
					.getUrl(WebServerConfig.todayWorkDeleteAction),
					toadayWorkEngine
							.deleteTodayWorkRequestParams(todayWorkModel),
					deleteToadyWorkHttpHandler);
		} else {
			endDeleteTodayWork(false, null);
		}

	}

	/**
	 * 删除工作结束
	 * 
	 * @param todayWorkModel
	 */
	private void endDeleteTodayWork(boolean isSuccess, String msg) {
		// 取消登录框
		if (waittingAlertDialog != null) {
			waittingAlertDialog.dismiss();
			waittingAlertDialog = null;
		}
		if (isSuccess) {
			// 成功，从新加载列表，考虑不重新请求，只是移除，刷新
			// startGetToadyWork(startPageNumber, true);
			todayWorkModelList
					.remove(onXLVChildClickListener.selectTodayWorkModel);
			List<TodayWorkModel> tmp = new ArrayList<TodayWorkModel>();
			tmp.addAll(todayWorkModelList);
			todayWorkDateList.clear();
			todayWorkModelList.clear();
			initTodayWorkList(tmp);
		} else {
			// 失败
			msg = TextUtils.isEmpty(msg) ? getResources().getString(
					R.string.common_string_unknown_mistake) : msg;
			Toast.makeText(activityContext, msg, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 完成工作
	 * 
	 * @param todayWorkModel
	 */
	private void startCompleteTodayWork(TodayWorkModel todayWorkModel) {
		// 开启等待框
		waittingAlertDialog = dialogTool.getWaittingDialog(-1, getResources()
				.getString(R.string.common_string_Loading));
		waittingAlertDialog.show();
		if (todayWorkModel != null) {
			asyncHttpClient.post(WebServerConfig
					.getUrl(WebServerConfig.todayWorkCompleteAction),
					toadayWorkEngine.completeRequestParams(todayWorkModel),
					completeToadyWorkHttpHandler);
		} else {
			endCompleteTodayWork(false, null);
		}

	}

	/**
	 * 完成工作结束
	 * 
	 * @param todayWorkModel
	 */
	private void endCompleteTodayWork(boolean isSuccess, String msg) {
		// 取消登录框
		if (waittingAlertDialog != null) {
			waittingAlertDialog.dismiss();
			waittingAlertDialog = null;
		}
		if (isSuccess) {
			// 成功，从新加载列表，可以考虑不先加载，直接改变状态，更新adapter
			// startGetToadyWork(startPageNumber, true);
			onXLVChildClickListener.selectTodayWorkModel.setState("1");
			toadayWorkXLVAdapter.notifyDataSetChanged();
		} else {
			// 失败
			msg = TextUtils.isEmpty(msg) ? getResources().getString(
					R.string.common_string_unknown_mistake) : msg;
			Toast.makeText(activityContext, msg, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 工作请求回调类
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class GetToadyWorkHttpHandler extends
			BaseJsonHttpResponseHandler<ToadayWorkListResponseModel> {
		private String errorMsg;

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable arg2,
				String arg3, ToadayWorkListResponseModel arg4) {
			errorMsg = null;
			errorMsg = getStringFromThrowable(arg2);
			endGetToadyWork(false, errorMsg, null);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String arg2,
				ToadayWorkListResponseModel arg3) {
			errorMsg = null;
			// 成功，不仅是网络请求成功，也得是验证成功，才是成功
			if (arg3 == null) {
				// 表示返回异常，不成功
				endGetToadyWork(false, null, null);
			} else {
				endGetToadyWork(true, null, arg3);
			}
		}

		@Override
		protected ToadayWorkListResponseModel parseResponse(String arg0)
				throws Throwable {
			return new ObjectMapper().readValues(
					new JsonFactory().createParser("{\""
							+ ToadayWorkListResponseModel.OUTKEY + "\":" + arg0
							+ "}"), ToadayWorkListResponseModel.class).next();

		}

	}

	/**
	 * 工作 删除 回调类
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class DeleteToadyWorkHttpHandler extends
			BaseJsonHttpResponseHandler<CommonResponseModel> {
		private String errorMsg;

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable arg2,
				String arg3, CommonResponseModel arg4) {
			errorMsg = null;
			errorMsg = getStringFromThrowable(arg2);
			endDeleteTodayWork(false, errorMsg);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String arg2,
				CommonResponseModel arg3) {
			errorMsg = null;
			// 成功，不仅是网络请求成功，也得是验证成功，才是成功
			if (arg3 != null && arg3.isResult()) {
				endDeleteTodayWork(true, null);
			} else {
				// 表示返回异常，不成功
				endDeleteTodayWork(false, null);
			}
		}

		@Override
		protected CommonResponseModel parseResponse(String arg0)
				throws Throwable {
			return new ObjectMapper().readValues(
					new JsonFactory().createParser(arg0.substring(1,
							arg0.length() - 1)), CommonResponseModel.class)
					.next();

		}

	}

	/**
	 * 工作 完成 回调类
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class CompleteToadyWorkHttpHandler extends
			BaseJsonHttpResponseHandler<CommonResponseModel> {
		private String errorMsg;

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable arg2,
				String arg3, CommonResponseModel arg4) {
			errorMsg = null;
			errorMsg = getStringFromThrowable(arg2);
			endCompleteTodayWork(false, errorMsg);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String arg2,
				CommonResponseModel arg3) {
			errorMsg = null;
			// 成功，不仅是网络请求成功，也得是验证成功，才是成功
			if (arg3 != null && arg3.isResult()) {
				endCompleteTodayWork(true, null);
			} else {
				// 表示返回异常，不成功
				endCompleteTodayWork(false, null);
			}
		}

		@Override
		protected CommonResponseModel parseResponse(String arg0)
				throws Throwable {
			return new ObjectMapper().readValues(
					new JsonFactory().createParser(arg0.substring(1,
							arg0.length() - 1)), CommonResponseModel.class)
					.next();

		}

	}

	@Override
	protected void onResume() {
		// 当新添加，或者删除后，需要从新加载数据
		todayWorkDateList.clear();
		todayWorkModelList.clear();
		startGetToadyWork(startPageNumber, true);
		super.onResume();
	}

	/**
	 * 当二级列表，的工作被长按时候的事件
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class OnXLVChildClickListener implements OnItemLongClickListener {
		public TodayWorkModel selectTodayWorkModel;

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			// model已经在对象中，判断tag中的对象是否不为null，为null，则为group
			if (view.getTag(R.integer.activity_today_work_list_apater_tag_key) != null) {
				selectTodayWorkModel = (TodayWorkModel) view
						.getTag(R.integer.activity_today_work_list_apater_tag_key);
				// 展示操作框
				operationDialog.show();
			}
			return false;
		}
	}

	/**
	 * 列表事件完成后，调用的
	 */
	private void onLoadFinish() {
		activity_today_work_xlv.stopRefresh();
		activity_today_work_xlv.stopLoadMore();
		activity_today_work_xlv.setRefreshTime(DateTime.now().toString(
				"yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 列表事件监听器
	 * 
	 * @author Administrator
	 * 
	 */
	private class OnXLVEventListener implements IXListViewListener {

		@Override
		public synchronized void onRefresh() {
			if (waittingAlertDialog == null) {
				// 刷新数据
				todayWorkDateList.clear();
				todayWorkModelList.clear();
				currentPageNumber = startPageNumber;
				startGetToadyWork(currentPageNumber, false);
			}
		}

		@Override
		public synchronized void onLoadMore() {
			// 加载更多
			if (waittingAlertDialog == null) {
				// 加载更多，所以页数家1，如果数据为空，则-1
				currentPageNumber += 1;
				startGetToadyWork(currentPageNumber, false);
			}
		}

	}
}
